<?php
include dirname(dirname(__FILE__)) . '/conf.php';
include SERVER_ROOT . 'public/saetv2.ex.class.php';
include SERVER_ROOT . 'public/db_weibo.php';

$uid = 1346818450;
$token = get_token($uid, WB_AKEY);
$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $token );

$favorites  = $c->get_favorites(1, 0);
$total = isset($favorites['total_number']) ? $favorites['total_number'] : 0;
if (!$total) exit('No favorite!');

// 设置分页
$size = 20;
$maxpage = ceil($total / $size);
$page_arr = array();
for ($page = 1; $page <= $maxpage; $page++){
	$page_arr[] = $page;
}

$exist_repeat = 0;
foreach ($page_arr as $page){
    $favorites = $c->get_favorites($page, $size);
    $fav = $favorites['favorites'];
    foreach ($fav as $favorite){
        $status = $favorite['status'];
        $favtime = conv_time($favorite['favorited_time']);
        $mid = $status['mid'];
        
        // 添加收藏
        $re = favorite_exist($uid, $mid);
        if ($re){
        	// 之前的都已经收藏过了，抓取到此为止
        	$exist_repeat = 1;
        }else{
        	add_favorite($mid, $uid, $favtime);

	        // 添加内容
	        if (isset($status['retweeted_status'])){
	            $raw_status = $status['retweeted_status'];
	            $raw_mid = $raw_status['mid'];
	
	            // 转发微博
	            insert_content($status, $raw_mid);
	            // 原微博
	            insert_content($raw_status);
	        }else{
	            insert_content($status);
	        }
        }

    }
    
    // 抓取结束
    if ($exist_repeat){
    	exit;
    }
}



function insert_content($contents, $raw_mid=0){
    if (isset($contents['deleted']) && $contents['deleted'] == 1) return false;

    $mid = $contents['mid'];
    $content = $contents['text'];
    $ctime = conv_time($contents['created_at']);
    $small_pic = isset($contents['thumbnail_pic']) ? $contents['thumbnail_pic'] : '';
    $middle_pic = isset($contents['bmiddle_pic']) ? $contents['bmiddle_pic'] : '';
    $large_pic = isset($contents['original_pic']) ? $contents['original_pic'] : '';
    $source_name = strip_tags($contents['source']);
    $source_url = get_html_url($contents['source']);

    $user = $contents['user'];
    $uid = $user['idstr'];
    $name = $user['name'];
    $gender = $user['gender'];
    $reg_time = conv_time($user['created_at']);
    $description = $user['description'];
    $province = $user['province'];
    $city = $user['city'];
    $location = $user['location'];
    $url = $user['url'];
    $domain = $user['domain'];
    $weihao = $user['weihao'];

    // 添加微博
    $re = mblog_exist($mid);
    if (!$re){
        add_mblog($mid, $uid, $content, $ctime, $small_pic, $middle_pic, $large_pic, $source_url, $source_name, $raw_mid);
    }

    // 添加用户
    $re = user_exist($uid);
    if (!$re){
        add_user($uid, $name, $gender, $reg_time, $description, $province, $city, $location, $url, $domain, $weihao);
    }
}

?>